<!DOCTYPE html>












  


<html class="theme-next gemini use-motion" lang="zh-CN">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2"/>
<meta name="theme-color" content="#222">












<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />






















<link href="/little-eight-china.github.io/lib/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css" />

<link href="/little-eight-china.github.io/css/main.css?v=6.3.0" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/little-eight-china.github.io/images/apple-touch-icon-next.png?v=6.3.0">


  <link rel="icon" type="image/png" sizes="32x32" href="/little-eight-china.github.io/images/favicon-32x32-next.png?v=6.3.0">


  <link rel="icon" type="image/png" sizes="16x16" href="/little-eight-china.github.io/images/favicon-16x16-next.png?v=6.3.0">


  <link rel="mask-icon" href="/little-eight-china.github.io/images/logo.svg?v=6.3.0" color="#222">









<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/little-eight-china.github.io/',
    scheme: 'Gemini',
    version: '6.3.0',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":true,"scrollpercent":false,"onmobile":false},
    fancybox: false,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  




  <meta name="description" content="装配bean它提供了三种主要的装配机制：  隐式的Bean发现机制和自动装配 在Java中进行显式配置 在XML中进行显式配置  自动化装配Bean 组件扫描（Component Scanning）：Spring会自动发现应用上下文中所创建的Bean 自动装配（Autowired）：Spring自动满足Bean之间的依赖  @Component这个注解表明该类会作为组件类（还有个类似的注解--@N">
<meta name="keywords" content="little_eight">
<meta property="og:type" content="article">
<meta property="og:title" content="Spring实战笔记（一）">
<meta property="og:url" content="http://yoursite.com/2018/10/01/Spring实战笔记（一）/index.html">
<meta property="og:site_name" content="八达博客">
<meta property="og:description" content="装配bean它提供了三种主要的装配机制：  隐式的Bean发现机制和自动装配 在Java中进行显式配置 在XML中进行显式配置  自动化装配Bean 组件扫描（Component Scanning）：Spring会自动发现应用上下文中所创建的Bean 自动装配（Autowired）：Spring自动满足Bean之间的依赖  @Component这个注解表明该类会作为组件类（还有个类似的注解--@N">
<meta property="og:locale" content="zh-CN">
<meta property="og:updated_time" content="2019-02-27T13:41:58.855Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Spring实战笔记（一）">
<meta name="twitter:description" content="装配bean它提供了三种主要的装配机制：  隐式的Bean发现机制和自动装配 在Java中进行显式配置 在XML中进行显式配置  自动化装配Bean 组件扫描（Component Scanning）：Spring会自动发现应用上下文中所创建的Bean 自动装配（Autowired）：Spring自动满足Bean之间的依赖  @Component这个注解表明该类会作为组件类（还有个类似的注解--@N">






  <link rel="canonical" href="http://yoursite.com/2018/10/01/Spring实战笔记（一）/"/>



<script type="text/javascript" id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title>Spring实战笔记（一） | 八达博客</title>
  









  <noscript>
  <style type="text/css">
    .use-motion .motion-element,
    .use-motion .brand,
    .use-motion .menu-item,
    .sidebar-inner,
    .use-motion .post-block,
    .use-motion .pagination,
    .use-motion .comments,
    .use-motion .post-header,
    .use-motion .post-body,
    .use-motion .collection-title { opacity: initial; }

    .use-motion .logo,
    .use-motion .site-title,
    .use-motion .site-subtitle {
      opacity: initial;
      top: initial;
    }

    .use-motion {
      .logo-line-before i { left: initial; }
      .logo-line-after i { right: initial; }
    }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/little-eight-china.github.io/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">八达博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
    
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>



<nav class="site-nav">
  
    <ul id="menu" class="menu">
      
        
        
        
          
          <li class="menu-item menu-item-home">
    <a href="/little-eight-china.github.io/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-home"></i> <br />首页</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-archives">
    <a href="/little-eight-china.github.io/archives/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />归档<span class="badge">15</span></a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-categories">
    <a href="/little-eight-china.github.io/categories/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-th"></i> <br />分类<span class="badge">4</span></a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-tags">
    <a href="/little-eight-china.github.io/tags/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />标签<span class="badge">2</span></a>
  </li>

      
      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />搜索</a>
        </li>
      
    </ul>
  

  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



  



</div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
            

          
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/little-eight-china.github.io/2018/10/01/Spring实战笔记（一）/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/little-eight-china.github.io/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="八达博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Spring实战笔记（一）
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">

            
            
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              

              
                
              

              <time title="创建时间：2018-10-01 16:20:23" itemprop="dateCreated datePublished" datetime="2018-10-01T16:20:23+00:00">2018-10-01</time>
            

            
              

              
                
                <span class="post-meta-divider">|</span>
                

                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                
                  <span class="post-meta-item-text">更新于</span>
                
                <time title="修改时间：2019-02-27 13:41:58" itemprop="dateModified" datetime="2019-02-27T13:41:58+00:00">2019-02-27</time>
              
            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/little-eight-china.github.io/categories/spring/" itemprop="url" rel="index"><span itemprop="name">spring</span></a></span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="装配bean"><a href="#装配bean" class="headerlink" title="装配bean"></a>装配bean</h2><p>它提供了三种主要的装配机制：</p>
<ul>
<li>隐式的Bean发现机制和自动装配</li>
<li>在Java中进行显式配置</li>
<li>在XML中进行显式配置</li>
</ul>
<h3 id="自动化装配Bean"><a href="#自动化装配Bean" class="headerlink" title="自动化装配Bean"></a>自动化装配Bean</h3><ul>
<li>组件扫描（Component Scanning）：Spring会自动发现应用上下文中所创建的Bean</li>
<li>自动装配（Autowired）：Spring自动满足Bean之间的依赖</li>
</ul>
<h4 id="Component"><a href="#Component" class="headerlink" title="@Component"></a>@Component</h4><p>这个注解表明该类会作为组件类（还有个类似的注解--@Named(“bean name”)，用法一样。）</p>
<h4 id="ComponentScan"><a href="#ComponentScan" class="headerlink" title="@ComponentScan"></a>@ComponentScan</h4><p>不过，组件扫描默认是不开启的，用@ComponentScan注解，如果没有其他配置，它默认会扫描与配置类相同的包（包括这个包下的所有子包），查找带有@Component注解的类，并在Spring中自动为其创建一个Bean</p>
<h4 id="ComponentScan的属性"><a href="#ComponentScan的属性" class="headerlink" title="@ComponentScan的属性"></a>@ComponentScan的属性</h4><ul>
<li>basePackages,值为扫描对象包，如：@ComponentScan(basePackages={“first”,”second”…})</li>
<li>basePackageClasses，值为扫描对象类，如：@ComponentScan(basePackageClasses={“first”,”second”…})</li>
</ul>
<h4 id="Autowired（-Inject用法大致一样）"><a href="#Autowired（-Inject用法大致一样）" class="headerlink" title="@Autowired（@Inject用法大致一样）"></a>@Autowired（@Inject用法大致一样）</h4><p>自动装配，bean之间的依赖，有构造器、setter方法、其他方法注入。</p>
<pre><code>在构造器上加此注解，如下，表明当Spring创建BeanA的bean时，会通过这个构造器来进行实例化并且会传入一个可设置给BeanB类型的bean
</code></pre><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Component</span></span><br><span class="line"><span class="keyword">public</span> BeanA implement BeanDady&#123;</span><br><span class="line">    <span class="keyword">private</span> BeanB b；</span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">public</span> BeanA（BeanB b）&#123;</span><br><span class="line">        <span class="keyword">this</span>.b = b</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">&lt;!--more--&gt;</span><br></pre></td></tr></table></figure>
<pre><code>用在属性的setter方法上，比如：
</code></pre><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Component</span></span><br><span class="line"><span class="keyword">public</span> BeanA implement BeanDady&#123;</span><br><span class="line">    <span class="keyword">private</span> BeanB b；</span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> setBeanB（BeanB b）&#123;</span><br><span class="line">        <span class="keyword">this</span>.b = b</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<pre><code>用在方法上,比如：
</code></pre><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Component</span></span><br><span class="line"><span class="keyword">public</span> BeanA implement BeanDady&#123;</span><br><span class="line">    <span class="keyword">private</span> BeanB b；</span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> test（BeanB b）&#123;</span><br><span class="line">        <span class="keyword">this</span>.b = b</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>不管什么方式，Spring都会尝试满足方法参数上所声明的依赖。假如有且只有一个bean匹配依赖需求的话，那么这个bean将会被装配起来，其他情况的话，在应用上下文创建时，Spring会抛出异常。为了避免异常，你可以将@Autowired的属性required设置为false<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Autowired</span>(required=<span class="keyword">false</span>)</span><br></pre></td></tr></table></figure></p>
<p>设置false后，如果没有匹配的bean，Spring会设置这个bean为未装配的状态，当然你的代码也有可能会出现空指针异常。</p>
<h3 id="通过Java代码装配bean"><a href="#通过Java代码装配bean" class="headerlink" title="通过Java代码装配bean"></a>通过Java代码装配bean</h3><h4 id="Configuration"><a href="#Configuration" class="headerlink" title="@Configuration"></a>@Configuration</h4><p>该注解表明这个类是一个配置类</p>
<h3 id="Bean"><a href="#Bean" class="headerlink" title="Bean"></a>Bean</h3><p>声明bean，我们给配置类里的方法加上此注解<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Configuratione</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">BeanConfig</span></span>&#123;</span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> BeanA <span class="title">beanA</span><span class="params">()</span></span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> BeanA();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>@Bean注解会告诉Spring这个方法将会返回一个对象，该对象要注册为Spring应用上下文的bean。默认情况下，bean的id跟此方法名一样，你也可以设置@Bean的属性name来指定一个不同的名字<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Bean</span>(name=<span class="string">"xxx"</span>)</span><br></pre></td></tr></table></figure></p>
<h3 id="通过XML装配bean"><a href="#通过XML装配bean" class="headerlink" title="通过XML装配bean"></a>通过XML装配bean</h3><p>不喜欢这种，，，</p>
<h4 id="声明一个简单的bean"><a href="#声明一个简单的bean" class="headerlink" title="声明一个简单的bean"></a>声明一个简单的bean</h4><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"beanA"</span> <span class="attr">class</span>=<span class="string">"com.BeanA"</span>/&gt;</span></span><br></pre></td></tr></table></figure>
<h3 id="小结"><a href="#小结" class="headerlink" title="小结"></a>小结</h3><p>建议使用自动化配置，减少维护成本。<br><a id="more"></a></p>
<h2 id="高技装配"><a href="#高技装配" class="headerlink" title="高技装配"></a>高技装配</h2><h3 id="Primary"><a href="#Primary" class="headerlink" title="@Primary"></a>@Primary</h3><p>在声明bean时，会有多个匹配的可能，比如BeanDady是一个接口，实现类有BeanA、BeanB<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Autowired</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setBean</span><span class="params">(BeanDady beanDady)</span></span>&#123;</span><br><span class="line">    <span class="keyword">this</span>.beanDady = beanDady;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>在组件扫描时，Spring就无法判断是装配哪个然后出现异常，所以我们将这个@Primary注解加到指定的类或者方法上，就可成为匹配首选,在匹配群里，此注解只能是唯一。<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Component</span></span><br><span class="line"><span class="meta">@Primary</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">BeanA</span> <span class="title">implement</span> <span class="title">BeanDady</span></span>&#123;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Bean</span></span><br><span class="line"><span class="meta">@Primary</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> BeanA <span class="title">beanA</span><span class="params">()</span></span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> BeanA();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>当然xml方式也有。。<br><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"beanA"</span> <span class="attr">class</span>=<span class="string">"com.BeanA"</span> <span class="attr">primary</span>=<span class="string">"true"</span>/&gt;</span></span><br></pre></td></tr></table></figure></p>
<h3 id="Qualifier"><a href="#Qualifier" class="headerlink" title="@Qualifier"></a>@Qualifier</h3><p>这个注解是使用限定符的主要方式，在注入的时候指定想要注入的bean<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Autowried</span></span><br><span class="line"><span class="meta">@Qualifier</span>(<span class="string">"beanA"</span>)</span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setBean</span><span class="params">(BeanDady beanDady)</span></span>&#123;</span><br><span class="line">    <span class="keyword">this</span>.beanDady = beanDady;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>这个注解的值默认是bean的id，当然你也可以自定义限定符,这样匹配的时候就以这个“a”为值，跟@Primary一样，此注解只能唯一<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Component</span></span><br><span class="line"><span class="meta">@Qualifier</span>(<span class="string">"a"</span>)</span><br><span class="line"><span class="keyword">public</span> BeanA implement BeanDady&#123;&#125;</span><br></pre></td></tr></table></figure></p>
<h2 id="bean的作用域"><a href="#bean的作用域" class="headerlink" title="bean的作用域"></a>bean的作用域</h2><p>Spring定义了多种作用域，可以基于这些作用域创建bean</p>
<ul>
<li>单例（singleton）：在整个应用中，只创建bean的一个实例</li>
<li>原型（prototype）：每次注入或者通过Spring应用上下文获取的时候，都会创建一个新的bean实例</li>
<li>会话（session）：在web应用中，为每个会话创建一个bean实例</li>
<li>请求（request）：在web应用中，为每个请求创建一个bean实例</li>
</ul>
<h3 id="Scope"><a href="#Scope" class="headerlink" title="@Scope"></a>@Scope</h3><p>单例是默认的作用域，如果想选择其他作用域，在bean的类加上此注解,值的话，为了安全跟不易出错，用ConfigurationBeanFactory.SCOPE_PROTOTYPE常量更好。<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Component</span></span><br><span class="line"><span class="meta">@Scope</span>(<span class="string">"prototype"</span>)</span><br><span class="line"><span class="comment">//这个更好。。 @Scope(ConfigurationBeanFactory.SCOPE_PROTOTYPE)</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">BeanA</span>...</span></span><br></pre></td></tr></table></figure></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Bean</span></span><br><span class="line"><span class="meta">@Scope</span>(ConfigurationBeanFactory.SCOPE_PROTOTYPE)</span><br><span class="line"><span class="keyword">public</span> BeanA beanA（）&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> BeanA（）；</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>当然xml也有。。<br><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"beanA"</span> <span class="attr">class</span>=<span class="string">"com.BeanA"</span> <span class="attr">scope</span>=<span class="string">"prototype"</span>/&gt;</span></span><br></pre></td></tr></table></figure></p>
<h2 id="面向切面编程"><a href="#面向切面编程" class="headerlink" title="面向切面编程"></a>面向切面编程</h2><h3 id="AOP术语"><a href="#AOP术语" class="headerlink" title="AOP术语"></a>AOP术语</h3><ul>
<li>通知（advice）：定义切面是什么以及什么时候使用</li>
<li>切点（poincut）：定义切面在哪里</li>
<li>连接点（join point）：所有可能的切面</li>
<li>切面（aspect）：通知和切点的结合</li>
<li>引入（introduction）：向现有的类加入新方法或者属性</li>
<li>织入（weaving）：</li>
</ul>
<h4 id="通知"><a href="#通知" class="headerlink" title="通知"></a>通知</h4><ul>
<li>前置通知（before）：在目标方法被调用前通知功能</li>
<li>后置通知（after）：在目标方法完成之后通知功能</li>
<li>返回通知（after-retrning）：在目标成功执行后调用通知</li>
<li>异常通知（after-throwing）：在目标方法抛出异常后通知</li>
<li>环绕通知（around）：通知包裹了被通知的方法，在被通知的方法调用之前和之后执行自定义的行为</li>
</ul>
<h3 id="编写切面"><a href="#编写切面" class="headerlink" title="编写切面"></a>编写切面</h3><h4 id="编写切点"><a href="#编写切点" class="headerlink" title="编写切点"></a>编写切点</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">execution(* com.Test.test(..)) &amp;&amp; within(com.*)</span><br></pre></td></tr></table></figure>
<ul>
<li>execution（），表示使用这种指示器</li>
<li>里面的“*”，这里表示方法返回值的类型，星号表示全部</li>
<li>com.Test.test(..),指定类型和方法名，括号的..代表不在乎这个方法的参数是什么</li>
<li>&amp;&amp;,和的意思，可选，后面的within（com.*）代表仅匹配com包</li>
</ul>
<h4 id="Aspect、-Before、-AfterReturning、-AfterThrowing"><a href="#Aspect、-Before、-AfterReturning、-AfterThrowing" class="headerlink" title="@Aspect、@Before、@AfterReturning、@AfterThrowing"></a>@Aspect、@Before、@AfterReturning、@AfterThrowing</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Aspect</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Qiemian</span></span>&#123;</span><br><span class="line">    <span class="comment">//调用之前，其他类型通知类似</span></span><br><span class="line">    <span class="meta">@Before</span>(<span class="string">"execution(* com.Test.test(..))"</span>)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">before</span><span class="params">()</span></span>&#123;&#125;</span><br><span class="line">    ...</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="Pointcut"><a href="#Pointcut" class="headerlink" title="@Pointcut"></a>@Pointcut</h4><p>当然每次都这么写切点表达式不麻烦死，所以这里可以用这个注解<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Aspect</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Qiemian</span> </span>&#123;</span><br><span class="line">    <span class="comment">//定义切点的方法,里面的实现最好是空的</span></span><br><span class="line">    <span class="meta">@Pointcut</span>(<span class="string">"execution(* com.Test.test(..))"</span>)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">pointcutMethod</span><span class="params">()</span>  </span>&#123;&#125;</span><br><span class="line">    <span class="comment">//调用之前，其他类型通知类似</span></span><br><span class="line">    <span class="meta">@Before</span>(<span class="string">"pointcutMethod()"</span>)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">before</span><span class="params">()</span> </span>&#123;&#125;</span><br><span class="line">    ...</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<h4 id="Around"><a href="#Around" class="headerlink" title="@Around"></a>@Around</h4><p>这个通知注解也是其他注解（@After是一定执行的。）的整合<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Qiemian</span> </span>&#123;</span><br><span class="line">    <span class="comment">//定义切点的方法,里面的实现最好是空的</span></span><br><span class="line">    <span class="meta">@Pointcut</span>(<span class="string">"execution(* com.Test.test(..))"</span>)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">pointcutMethod</span><span class="params">()</span>  </span>&#123;&#125;</span><br><span class="line">    <span class="comment">//环绕通知 </span></span><br><span class="line">    <span class="meta">@Around</span>(<span class="string">"pointcutMethod()"</span>)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">around</span><span class="params">(ProceedingJoinPoint jp)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">try</span>&#123;</span><br><span class="line">            <span class="comment">//这里是调用之前通知</span></span><br><span class="line">            System.out.println(<span class="string">"调用之前"</span>);</span><br><span class="line">            <span class="comment">//调用这个方法后，代表调用之后</span></span><br><span class="line">            jp.proceed();</span><br><span class="line">            <span class="comment">// 这里是调用执行成功之后通知</span></span><br><span class="line">            System.out.println(<span class="string">"调用执行成功之后"</span>);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (Exection e)&#123;</span><br><span class="line">            System.out.println(<span class="string">"抛异常之后"</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>当然xml也有，这里不搞了。</p>

      
    </div>

    

    
    
    

    

    

    
    <div>
      
        <div>
    
        <div style="text-align:center;color: #ccc;font-size:14px;">
            -------------本文结束
            <i class="fa fa-paw"></i>
            感谢您的阅读-------------
        </div>
    
</div>

      
    </div>
    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/little-eight-china.github.io/tags/little-eight/" rel="tag"># little_eight</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/little-eight-china.github.io/2018/09/27/Linux的基本命令入门/" rel="next" title="Linux的基本命令入门">
                <i class="fa fa-chevron-left"></i> Linux的基本命令入门
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/little-eight-china.github.io/2018/10/03/java面试题（二）/" rel="prev" title="java面试题（二）">
                java面试题（二） <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          

  
    <div class="comments" id="comments">
      <div id="lv-container" data-id="city" data-uid="MTAyMC8zODE4Ni8xNDcxNA=="></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name"></p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/little-eight-china.github.io/archives/">
                
                    <span class="site-state-item-count">15</span>
                    <span class="site-state-item-name">日志</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-categories">
                  <a href="/little-eight-china.github.io/categories/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">4</span>
                    <span class="site-state-item-name">分类</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-tags">
                  <a href="/little-eight-china.github.io/tags/index.html">
                    
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">2</span>
                    <span class="site-state-item-name">标签</span>
                  </a>
                </div>
              
            </nav>
          

          

          
            <div class="links-of-author motion-element">
              
                <span class="links-of-author-item">
                  <a href="https://github.com/little-eight-china" target="_blank" title="GitHub"><i class="fa fa-fw fa-github"></i>GitHub</a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://blog.csdn.net/h295928126" target="_blank" title="CSDN"><i class="fa fa-fw fa-crosshairs"></i>CSDN</a>
                  
                </span>
              
            </div>
          

          
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-block">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-link"></i>
                成人链接
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="https://acris.me/" title="acris" target="_blank">acris</a>
                  </li>
                
              </ul>
            </div>
          

          
            
          
          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#装配bean"><span class="nav-number">1.</span> <span class="nav-text">装配bean</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#自动化装配Bean"><span class="nav-number">1.1.</span> <span class="nav-text">自动化装配Bean</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#Component"><span class="nav-number">1.1.1.</span> <span class="nav-text">@Component</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#ComponentScan"><span class="nav-number">1.1.2.</span> <span class="nav-text">@ComponentScan</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#ComponentScan的属性"><span class="nav-number">1.1.3.</span> <span class="nav-text">@ComponentScan的属性</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#Autowired（-Inject用法大致一样）"><span class="nav-number">1.1.4.</span> <span class="nav-text">@Autowired（@Inject用法大致一样）</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#通过Java代码装配bean"><span class="nav-number">1.2.</span> <span class="nav-text">通过Java代码装配bean</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#Configuration"><span class="nav-number">1.2.1.</span> <span class="nav-text">@Configuration</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Bean"><span class="nav-number">1.3.</span> <span class="nav-text">Bean</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#通过XML装配bean"><span class="nav-number">1.4.</span> <span class="nav-text">通过XML装配bean</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#声明一个简单的bean"><span class="nav-number">1.4.1.</span> <span class="nav-text">声明一个简单的bean</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#小结"><span class="nav-number">1.5.</span> <span class="nav-text">小结</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#高技装配"><span class="nav-number">2.</span> <span class="nav-text">高技装配</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#Primary"><span class="nav-number">2.1.</span> <span class="nav-text">@Primary</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Qualifier"><span class="nav-number">2.2.</span> <span class="nav-text">@Qualifier</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#bean的作用域"><span class="nav-number">3.</span> <span class="nav-text">bean的作用域</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#Scope"><span class="nav-number">3.1.</span> <span class="nav-text">@Scope</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#面向切面编程"><span class="nav-number">4.</span> <span class="nav-text">面向切面编程</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#AOP术语"><span class="nav-number">4.1.</span> <span class="nav-text">AOP术语</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#通知"><span class="nav-number">4.1.1.</span> <span class="nav-text">通知</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#编写切面"><span class="nav-number">4.2.</span> <span class="nav-text">编写切面</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#编写切点"><span class="nav-number">4.2.1.</span> <span class="nav-text">编写切点</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#Aspect、-Before、-AfterReturning、-AfterThrowing"><span class="nav-number">4.2.2.</span> <span class="nav-text">@Aspect、@Before、@AfterReturning、@AfterThrowing</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#Pointcut"><span class="nav-number">4.2.3.</span> <span class="nav-text">@Pointcut</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#Around"><span class="nav-number">4.2.4.</span> <span class="nav-text">@Around</span></a></li></ol></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      
        <div class="back-to-top">
          <i class="fa fa-arrow-up"></i>
          
        </div>
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2019</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder"></span>

  

  
</div>



<!-- 统计访问数 -->
<div>
<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
<span id="busuanzi_container_site_pv" style='display:none'>
    本站总访问量 <span id="busuanzi_value_site_pv"></span> 次
    <span class="post-meta-divider">|</span>
</span>
<span id="busuanzi_container_site_uv" style='display:none'>
    有<span id="busuanzi_value_site_uv"></span>人看过我的博客啦
</span>
</div>

        








        
      </div>
    </footer>

    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>


























  
  
    <script type="text/javascript" src="/little-eight-china.github.io/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/little-eight-china.github.io/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/little-eight-china.github.io/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  


  


  <script type="text/javascript" src="/little-eight-china.github.io/js/src/utils.js?v=6.3.0"></script>

  <script type="text/javascript" src="/little-eight-china.github.io/js/src/motion.js?v=6.3.0"></script>



  
  


  <script type="text/javascript" src="/little-eight-china.github.io/js/src/affix.js?v=6.3.0"></script>

  <script type="text/javascript" src="/little-eight-china.github.io/js/src/schemes/pisces.js?v=6.3.0"></script>



  
  <script type="text/javascript" src="/little-eight-china.github.io/js/src/scrollspy.js?v=6.3.0"></script>
<script type="text/javascript" src="/little-eight-china.github.io/js/src/post-details.js?v=6.3.0"></script>



  


  <script type="text/javascript" src="/little-eight-china.github.io/js/src/bootstrap.js?v=6.3.0"></script>



  



  





  
    <script type="text/javascript">
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
  










  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/little-eight-china.github.io/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  

  
  

  

  

  

  

  

</body>
</html>
